package commonwebgroup.commonwebartifact.CommandHandle;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import commonwebgroup.commonwebartifact.Helper.ColorHelper;
import commonwebgroup.commonwebartifact.Helper.HttpHelper;
import commonwebgroup.commonwebartifact.Models.ApiResModel;
import commonwebgroup.commonwebartifact.functions.MyFunction;
import commonwebgroup.commonwebartifact.util.CommandUtil;
import commonwebgroup.commonwebartifact.util.ResponseUtil;
import commonwebgroup.commonwebartifact.util.StringUtil;
import de.tr7zw.nbtapi.NBT;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

import java.util.Map;
import java.util.Objects;


public class CommandPlayerHandle {

    private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();

    public static boolean Execute(Player player, String[] args, String apiUrl, String apiKey, HttpHelper httpHelper) {
        // valid
        Objects.requireNonNull(player, "player is not allow null");
        // 参数校验
        if (!CommandUtil.checkArgs(args, 2, player)) {
            return false;
        }
        if (CommandUtil.isPushItem(args)) {
            //空物品拦截,不响应
            if (player.getInventory().getItemInMainHand().getType() == Material.AIR) return false;
            return pushItem(player, args, apiUrl, apiKey, httpHelper);
        } else if (CommandUtil.isPullItem(args)) {
            return pullItem(player, args, apiUrl, apiKey, httpHelper);
        } else {
            player.sendMessage(ColorHelper.Error("当前命令不支持！正确指格式是: mcm <push,pull> item"));
            return false;
        }
    }


    private static boolean pushItem(Player player, String[] args, String apiUrl, String apiKey, HttpHelper httpHelper) {

        return httpCommon(player, args, apiUrl, apiKey, httpHelper, () -> {
            // map
            //组装json数据
            Map<String, String> reqBindData = null;
            try {
                reqBindData = CommandUtil.getMapData(player, apiKey);
            } catch (Exception e) {
                player.sendMessage(ColorHelper.Error(e.getMessage()));
                return;
            }
            httpHelper.sendPostRequest(StringUtil.formatString(apiUrl, "putItem"), GSON.toJson(reqBindData))
                    .thenAccept(response -> {
                        if (!StringUtil.isEmpty(response)) {
                            //去除转义
                            response = httpHelper.escapedStrHandle(response);
                            System.out.println("响应的结果：" + response);
                            // 在这里处理响应
                            ResponseUtil.validResponse(response, ApiResModel.class, player,
                                    (apiResModel) -> {
                                        player.sendMessage(ColorHelper.Success("物品已传递成功,请前往终端查看,如有异常请联系OP"));
                                        player.getInventory().setItemInMainHand(new ItemStack(Material.AIR));
                                    }, (error) -> {
                                        player.sendMessage(ColorHelper.Error(error));
                                    });
                        } else {
                            player.sendMessage(ColorHelper.Error("获取信息失败！"));
                        }
                    }).exceptionally(e -> {
                        player.sendMessage(ColorHelper.Error(e.getMessage()));
                        return null;
                    });
        });
    }

    private static boolean pullItem(Player player, String[] args, String apiUrl, String apiKey, HttpHelper httpHelper) {

        return httpCommon(player, args, apiUrl, apiKey, httpHelper, () -> {
            // map
            Map<String, String> reqBindData = null;
            try {
                reqBindData = CommandUtil.getMapData(Bukkit.getVersion(), player, apiKey);
            } catch (Exception e) {
                player.sendMessage(ColorHelper.Error(e.getMessage()));
                return;
            }

            // 获取请求响应结果
            httpHelper.sendPostRequest(StringUtil.formatString(apiUrl, "pullItem"), GSON.toJson(reqBindData))
                    .thenAccept(response -> {
                        if (!StringUtil.isEmpty(response)) {
                            System.out.println("响应的结果：" + response);
                            //去除转义
                            response = httpHelper.escapedStrHandle(response);
                            String finalResponse = response;
                            ResponseUtil.validResponse(response, ApiResModel.class, player,
                                    (apiResModel) -> {
                                        // 在这里处理响应
                                        player.sendMessage(ColorHelper.Success("物品已接收成功,请前往终端查看,如有异常请联系OP"));
                                        player.getInventory().setItemInMainHand(new ItemStack(Material.AIR));
                                        ItemStack apiItemStack = NBT.itemStackFromNBT(NBT.parseNBT(finalResponse));
                                        player.getInventory().setItemInMainHand(apiItemStack);
                                    }, (error) -> {
                                        player.sendMessage(ColorHelper.Error(error));
                                    });
                        } else {
                            // 请求错误
                            player.sendMessage(ColorHelper.Error("获取信息失败！"));
                        }

                    }).exceptionally(e -> {
                        e.printStackTrace();
                        player.sendMessage(ColorHelper.Error(e.getMessage()));
                        return null;
                    });

        });


    }

    private static boolean httpCommon(Player player, String[] args, String apiUrl, String apiKey, HttpHelper httpHelper, MyFunction myFunction) {

        if (Objects.isNull(player)) {
            return false;
        }
        // valid
        try {
            CommandUtil.validPlayer(player);
        } catch (Exception e) {
            player.sendMessage(ColorHelper.Error(e.getMessage()));
            return false;
        }

        //
        if (!player.getInventory().getItemInMainHand().getType().isAir()) {
            player.sendMessage(ColorHelper.Error("获取物品前，主手不能拿着东西"));
            return false;
        }
        try {
            myFunction.start();
        } catch (Exception e) {
            player.sendMessage(ColorHelper.Error(e.getMessage()));
            return false;
        }


        return true;
    }
}


